using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Oops.Xna.Framework.Physics;
using Oops.Xna.Framework.Input;

namespace Oops.Xna.Framework.Testing.App
{
	public class Example7Screen : ExampleScreen
	{
		// Content.
		private Texture2D texture;
		private Model model;

		private CollisionMesh mesh;
		private Vector3 meshPosition = Vector3.Down * 50.0f;
		private Matrix meshOrientation = Matrix.CreateRotationZ(MathHelper.ToRadians(-10.0f));

		public Example7Screen(Game game) : base(game, "Example7") {	}

		#region ExampleScreen Members

		protected override void DrawWorld(Effect effect, EffectParameter world, EffectParameter texture)
		{
			ModelMesh mesh = this.model.Meshes[0];
			ModelMeshPart meshPart = mesh.MeshParts[0];

			this.GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;
			this.GraphicsDevice.Vertices[0].SetSource(mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);
			this.GraphicsDevice.Indices = mesh.IndexBuffer;

			// Draw the ground.
			world.SetValue(this.meshOrientation * Matrix.CreateTranslation(this.meshPosition));
			texture.SetValue(this.texture);
			effect.CommitChanges();

			this.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, meshPart.BaseVertex, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);
		}

		protected override void Reset()
		{
			// Start with 25 boxes and 50 spheres.
			this.Reset(25, 50);

			// Create the ground plane.  
			this.mesh = new CollisionMesh(new ModelCollisionMeshProxy(model));
						
			// Create a collision group and add the mesh.
			CollisionGroup collisionGroup = new CollisionGroup();
			collisionGroup.CollisionShapes.Add(this.mesh);
#if QUATERNION_ORIENTATION
            Quaternion orientation = Quaternion.CreateFromRotationMatrix(this.meshOrientation);
#else
			Matrix orientation = this.meshOrientation;
#endif
			collisionGroup.UpdateTransform(ref this.meshPosition, ref orientation);

			// Add the mesh's collision group to the collision system.
			this.physics.CollisionSystem.CollisionGroups.Add(collisionGroup);
		}

		#endregion

		#region DrawableGameComponent Members

		protected override void LoadContent()
		{
			// Load all the used graphic resources.
			this.texture = this.Game.GetContent().Load<Texture2D>(@".\Content\Textures\plane");
			this.model = this.Game.GetContent().Load<Model>(@".\Content\Models\example7");
			
			// Call inherited method.
			base.LoadContent();
		}

		#endregion
	}
}
